package com.monitor.app_monitor.service.quartz.utils;

import com.monitor.app_monitor.entity.CellectInfo;
import com.monitor.app_monitor.entity.ServiceList;
import com.monitor.app_monitor.entity.TaskDO;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Service
@Slf4j
public class QuartzManager {


    /**
     * 添加任务
     * 
     * @param appInfo
     * @throws SchedulerException
     */


    @Autowired
    private Scheduler scheduler;

    //测试任务
    public void addTestJon() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.TestJob";

            String JobName = "TestJob";
            String JobGroup = "common";
            String cronStr = "1 0 * * * ?";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);



            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());


            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //传输段数据监控
    public void addTrsSegNo() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.TrsSegInfo";

            String JobName = "TrsSegNo";
            String JobGroup = "YG_data_check";
            String cronStr = "0 */10 * * * ?";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);



            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());


            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail,trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //性能nce-s监控
    public void addPmNceS() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.PmNceS";

            String JobName = "PmNceS";
            String JobGroup = "cellect_file_info";
            String cronStr = "0 */2 * * * ?";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);



            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());


            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //性能采集文件信息
    public void addPmFileInfo() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.CellectPmFileSizeCheck";

            String JobName = "PmFileJob";
            String JobGroup = "cellect_file_info";
            String cronStr = "0 0 0/1 * * ? ";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);



            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());


            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //监控采集程序状态，检查是否存活
    public void addJob(ServiceList app) {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.ColectCheckJob";

            // 创建jobDetail实例，绑定Job实现类

            String JobName = String.valueOf(app.getId());
            String cronStr = "0 */2 * * * ?";
            String JobGroup = "cellect_app";



            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());
            final JobDataMap jobDataMap = new JobDataMap();

            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);
            jobDataMap.put("host",app.getHost());
            jobDataMap.put("owner",app.getOwner());
            jobDataMap.put("emsName",app.getEmsName());
            jobDataMap.put("networkForm",app.getNetworkForm());
            jobDataMap.put("emsIp",app.getEmsIp());
            jobDataMap.put("gitAdds",app.getGitAdds());
            jobDataMap.put("jarName",app.getJarName());
            jobDataMap.put("env",app.getEnv());
            jobDataMap.put("port",app.getPort());
            jobDataMap.put("developer",app.getDeveloper());
            jobDataMap.put("appDescribe",app.getAppDescribe());
            jobDataMap.put("note",app.getNote());
            jobDataMap.put("type",app.getType());
            jobDataMap.put("id",app.getId());

            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //采集文件状态监控，检查文件是否采集完成
    public void addJob(CellectInfo cellectInfo) {

        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.CellectDataCheck";

            // 创建jobDetail实例，绑定Job实现类

            String JobName = String.valueOf(cellectInfo.getEmsName()+cellectInfo.getResType());
            String JobGroup = "cellect_file_status";
            String cronStr = cellectInfo.getCellectTime();
            //cronStr = "0 */1 * * * ?";

            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());
            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);
            jobDataMap.put("emsName",cellectInfo.getEmsName());
            jobDataMap.put("resType",cellectInfo.getResType());
            jobDataMap.put("developer",cellectInfo.getDeveloper());

            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //添加一干文件大小行数监控并生成文件
    public void addJob(List<CellectInfo> cellectInfo) {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.CellectFileSizeCheck";

            // 创建jobDetail实例，绑定Job实现类

            String JobName = "cellectYgFileInfo";
            String JobGroup = "cellect_file_info";
            String cronStr = "0 0 0/1 * * ? ";


            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);
            jobDataMap.put("cellectList",cellectInfo);




            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());




            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //告警数据库数据监控
    public void addAlarmJob() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.AlarmNbMysql";

            // 创建jobDetail实例，绑定Job实现类

            String JobName = "AlarmNb";
            String JobGroup = "AlarmDatabases";
            String cronStr = "0 */20 * * * ?";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);


            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());



            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //添加时间格式化数据
    public void addDateInfoJob() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.DateInfo";

            // 创建jobDetail实例，绑定Job实现类

            String JobName = "DateInfo";
            String JobGroup = "common";
            String cronStr = "1 0 * * * ?";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);


            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());



            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //监控数据安ems分类
    public void addTableByEmsIpJob() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.DataNbCheckByEmsIp";
            String JobName = "DateInfoByEmsIp";
            String JobGroup = "YG_data_check";
            String cronStr = "* */20 * * * ?";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);

            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());



            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //监控二干文件大小行数
    public void addRGFileJob() {
        try {

            String beanInfo = "com.monitor.app_monitor.service.quartz.task.CellectRGFileSizeCheck";

            // 创建jobDetail实例，绑定Job实现类

            String JobName = "CellectRGFileSizeCheck";
            String JobGroup = "cellect_file_info";

            String cronStr = "0 0 16 * * ?";

            final JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("JobName",JobName);
            jobDataMap.put("JobGroup",JobGroup);

            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(beanInfo).newInstance()
                    .getClass());



            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobName, JobGroup).usingJobData(jobDataMap)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JobName, JobGroup)// 触发器key
                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).startNow().build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取所有计划中的任务列表
     *
     * @return
     * @throws SchedulerException
     */
    public List<TaskDO> getAllJob() throws SchedulerException {
        GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
        Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
        List<TaskDO> jobList = new ArrayList<TaskDO>();
        for (JobKey jobKey : jobKeys) {
            List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
            for (Trigger trigger : triggers) {
                TaskDO job = new TaskDO();
                job.setJobName(jobKey.getName());
                job.setJobGroup(jobKey.getGroup());
                job.setDescription("触发器:" + trigger.getKey());

                Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                job.setJobStatus(triggerState.name());
                if (trigger instanceof CronTrigger) {
                    CronTrigger cronTrigger = (CronTrigger) trigger;
                    String cronExpression = cronTrigger.getCronExpression();
                    job.setCronExpression(cronExpression);
                }
                jobList.add(job);
            }
        }
        return jobList;
    }
//
//
//    /**
//     * 所有正在运行的job
//     *
//     * @return
//     * @throws SchedulerException
//     */
//    public List<TaskDO> getRunningJob() throws SchedulerException {
//        List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
//        List<TaskDO> jobList = new ArrayList<TaskDO>(executingJobs.size());
//        for (JobExecutionContext executingJob : executingJobs) {
//            TaskDO job = new TaskDO();
//            JobDetail jobDetail = executingJob.getJobDetail();
//            JobKey jobKey = jobDetail.getKey();
//            Trigger trigger = executingJob.getTrigger();
//            job.setJobName(jobKey.getName());
//            job.setJobGroup(jobKey.getGroup());
//            job.setDescription("触发器:" + trigger.getKey());
//            Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
//            job.setJobStatus(triggerState.name());
//            if (trigger instanceof CronTrigger) {
//                CronTrigger cronTrigger = (CronTrigger) trigger;
//                String cronExpression = cronTrigger.getCronExpression();
//                job.setCronExpression(cronExpression);
//            }
//            jobList.add(job);
//        }
//        return jobList;
//    }
//
//    /**
//     * 暂停一个job
//     *
//     * @param task
//     * @throws SchedulerException
//     */
//    public void pauseJob(TaskDO task) throws SchedulerException {
//        JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
//        scheduler.pauseJob(jobKey);
//    }
//
//    /**
//     * 恢复一个job
//     *
//     * @param task
//     * @throws SchedulerException
//     */
//    public void resumeJob(TaskDO task) throws SchedulerException {
//        JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
//        scheduler.resumeJob(jobKey);
//    }
//
//    /**
//     * 删除一个job
//     *
//     * @param task
//     * @throws SchedulerException
//     */
//    public void deleteJob(String taskName) throws SchedulerException {
//        JobKey jobKey = JobKey.jobKey(taskName, "group");
//        scheduler.deleteJob(jobKey);
//    }
//
    /**
     * 立即执行job
     *
     * @param taskName
     * @throws SchedulerException
     */
    public void runJobNow(String taskName,String group ) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(taskName, group);
        scheduler.triggerJob(jobKey);
    }

}